//
//  KLMCodeLoginController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/12.
//

import UIKit

class KLMCodeLoginController: KLMBaseController {

    //倒计时
    var messageTimer: Timer?
    ///当前秒
    var currentTime: Int = 60
    
    @IBOutlet weak var logoView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var accountTextField: UITextField!
    @IBOutlet weak var pwdTextField: UITextField!
    @IBOutlet weak var sendCodeBtn: UIButton!
    @IBOutlet weak var agreeBtn: UIButton!
    @IBOutlet weak var agreeLabel: UILabel!
    
    @IBOutlet weak var userPrivacyBtn: UIButton!
    @IBOutlet weak var andLabel: UILabel!
    @IBOutlet weak var privacyPolicyBtn: UIButton!
    @IBOutlet weak var mobileLoginBtn: UIButton!
    @IBOutlet weak var pwdLoginBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupData()
    }
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        
        logoView.image = UIImage.image(withColor: appMainThemeColor, size: logoView.size, cornerRadius: 12)
        nameLabel.configStyle(with: "智谋纪", font: UIFont(safeName: "PingFangSC-Medium", size: 21), titleColor: rgba(38, 38, 38, 1))
        
        KLMLog("login")
        mobileLoginBtn.isEnabled = false
        mobileLoginBtn.configStyle(with: KLMLocalizable.LANGLOC("Log In"), font: UIFont(safeName: "PingFangSC-Regular", size: 18), titleColor: .white, bgImage: UIImage.init(color: appMainThemeColor))
        mobileLoginBtn.configStyle(bgImage: UIImage.init(color: appMainThemeColor.withAlphaComponent(0.5)), state: .disabled)
        
        pwdLoginBtn.configStyle(with: KLMLocalizable.LANGLOC("Code Log In"), font: UIFont(safeName: "PingFangSC-Regular", size: 18), titleColor: rgba(38, 38, 38, 1), bgImage: UIImage.init(color: rgba(239, 239, 239, 1)))
        
        mobileLoginBtn.layer.cornerRadius = mobileLoginBtn.height / 2
        mobileLoginBtn.clipsToBounds = true
        pwdLoginBtn.layer.cornerRadius = pwdLoginBtn.height / 2
        pwdLoginBtn.clipsToBounds = true
        
        NotificationCenter.default.addObserver(self, selector: #selector(setupData), name: .loginPageRefresh, object: nil)
        
        accountTextField.font = UIFont(safeName: "PingFangSC-Medium", size: 16)
        pwdTextField.font = UIFont(safeName: "PingFangSC-Medium", size: 16)
        accountTextField.placeholder = KLMLocalizable.LANGLOC("Please Enter Phone")
        pwdTextField.placeholder = KLMLocalizable.LANGLOC("Please Enter Code")
        accountTextField.addTarget(self, action: #selector(textChange(_:)), for: .editingChanged)
        pwdTextField.addTarget(self, action: #selector(textChange(_:)), for: .editingChanged)
        accountTextField.keyboardType = .phonePad
        pwdTextField.keyboardType = .numberPad
        pwdTextField.isSecureTextEntry = false
        pwdTextField.clearButtonMode = .whileEditing
        
        sendCodeBtn.configStyle(with: KLMLocalizable.LANGLOC("Get verification code"), font: UIFont(safeName: "PingFang-SC-Medium", size: 11), titleColor: rgba(51, 51, 51, 1), bgImage: UIImage(color: rgba(239, 239, 239, 1)))
        sendCodeBtn.configStyle(titleColor: rgba(51, 51, 51, 0.5), state: .disabled)
        sendCodeBtn.layer.cornerRadius = 2.0
        sendCodeBtn.layer.masksToBounds = true
        
        agreeLabel.text = KLMLocalizable.LANGLOC("I agree to")
        andLabel.text = KLMLocalizable.LANGLOC("And")
//        已阅读并同意《用户协议》和《隐私政策》
        privacyPolicyBtn.configStyle(with: "《" + KLMLocalizable.LANGLOC("Privacy Policy") + "》", titleColor: rgba(28, 136, 229, 1))
        userPrivacyBtn.configStyle(with: "《" + KLMLocalizable.LANGLOC("User Protocol") + "》", titleColor: rgba(28, 136, 229, 1))
        agreeBtn.configStyle(image: "icon_no_select")
        agreeBtn.configStyle(image: "icon_select", state: .selected)
    }
    
    @objc func setupData() {
        if let username = KLMUserDefault.getValue(for: .username) {
            self.accountTextField.text = username as? String
        }
//        if let password = KLMUserDefault.getValue(for: .password) {
//            self.pwdTextField.text = password as? String
//        }
    }
    @objc func textChange(_ textField: UITextField) {
        mobileLoginBtn.isEnabled = false
        if let account = accountTextField.text, !account.isEmpty, let pwd = pwdTextField.text, !pwd.isEmpty {
            mobileLoginBtn.isEnabled = true
        }
    }
    @IBAction func tapAgree(_ sender: UIButton) {
        sender.isSelected.toggle()
    }
    
    @IBAction func tapUserPrivacy(_ sender: UIButton) {
        let vc = WHWebViewController()
        vc.urlString = "https://www.kinglumi.com/about/privacy-policy"
        vc.loadingProgressColor = appMainThemeColor
        navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func tapPrivacyPolicy(_ sender: UIButton) {
        let vc = WHWebViewController()
        vc.urlString = "https://www.kinglumi.com/about/privacy-policy"
        vc.loadingProgressColor = appMainThemeColor
        navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func tapSendCode(_ sender: UIButton) {
        if agreeBtn.isSelected == false {
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Please agree to the Privacy Policy"))
            return
        }
        /// 发送验证码
        guard let text = KLMTool.isEmptyString(string: accountTextField.text) else {
            SVProgressHUD.showInfo(withStatus: accountTextField.placeholder)
            return
        }
        
        if !KLMVerifyManager.isPhone(phone: text) {
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("The mobile number format is incorrect"))
            return
        }
        SVProgressHUD.show()
        KLMRequest.getPhoneCode(phone: text) { response in
            SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Verification code has been sent"))
            
            ///开始倒计时
            self.startTimer()
        } failure: { error in
            KLMHttpShowError(error)
        }
    }
    @IBAction func tapMobileLogin(_ sender: UIButton) {
        // 手机+验证码登录
        if agreeBtn.isSelected {
            guard let phontText = KLMTool.isEmptyString(string: accountTextField.text) else {
                SVProgressHUD.showInfo(withStatus: accountTextField.placeholder)
                return
            }
            guard let passText = KLMTool.isEmptyString(string: pwdTextField.text) else {
                SVProgressHUD.showInfo(withStatus: pwdTextField.placeholder)
                return
            }
            if !KLMVerifyManager.isPhone(phone: phontText) {
                SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("The mobile number format is incorrect"))
                return
            }
            login(account: phontText, pwd: passText)
            
        } else {
            SVProgressHUD.showInfo(withStatus: KLMLocalizable.LANGLOC("Please agree to the Privacy Policy"))
        }
    }
    func login(account: String, pwd: String) {
        SVProgressHUD.show()
        KLMRequest.codeLogin(phone: account, code: pwd) { _ in
            SVProgressHUD.dismiss()
            ///进入主页面
            self.switchRootVc(vc: KLMTabBarController())
        } failure: { error in
            KLMHttpShowError(error)
        }
    }
    @IBAction func tapPwdLogin(_ sender: UIButton) {
        let vc = KLMLoginController()
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - 定时器
extension KLMCodeLoginController {
    private func startTimer() {
        stopTime()
        sendCodeBtn.isEnabled = false
        messageTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(UpdateTimer), userInfo: nil, repeats: true)
    }
    
    private func stopTime() {
        currentTime = 60
        if messageTimer != nil {
            messageTimer?.invalidate()
            messageTimer = nil
        }
    }
    
    @objc func UpdateTimer() {
        
        currentTime -= 1
        sendCodeBtn.setTitle(KLMLocalizable.LANGLOC("Get verification code")+"（\(currentTime)s）", for: .normal)
        if currentTime <= 0 {//结束
            stopTime()
            sendCodeBtn.isEnabled = true
            sendCodeBtn.setTitle(KLMLocalizable.LANGLOC("Get verification code"), for: .normal)
        }
    }
}
